const { ipcMain, BrowserWindow } = require('electron');
const WebSocket = require('ws');

class WebSocketManager {
  constructor(url, options = {}) {
    console.log("Start connect WebSocket url is '" + url+"'")
    this.url = url;
    this.options = options;
    this.ws = null;
    this.reconnectInterval = options.reconnectInterval || 5000; // 默认重连间隔为5秒
    this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // 默认最大重连尝试次数为10次
    this.reconnectAttempts = 0;
    this.init();
  }

  init() {
    if (!this.ws) {
    this.connect();
    }
    ipcMain.on('disconnect-websocket', () => {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    });
  }

  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.on('open', () => {
      console.log('WebSocket connection established');
      this.reconnectAttempts = 0; // 重置重连尝试次数
      BrowserWindow.getAllWindows().forEach((window) => {
        window.webContents.send('websocket-connected');
      });
    });

    this.ws.on('message', (message) => {
      let messageString = message instanceof Buffer ? message.toString('utf-8') : message; // 将 Buffer 转换为字符串
      console.log('Message from server:', messageString);
      // 广播消息到【主窗口、朋友圈窗口、通话窗口】
      // 聊天消息广播到主窗口和通话窗口
      BrowserWindow.getAllWindows().forEach((window) => {
        const messageObj = JSON.parse(messageString)
        if(window.customName=='Wechat') {
          window.webContents.send('websocket-message', messageString);
        }
      });
    });

    this.ws.on('close', (code, reason) => {
      if(code!==1000) {
        console.log(`WebSocket connection closed with code: ${code}, reason: ${reason}`);
        BrowserWindow.getAllWindows().forEach((window) => {
          window.webContents.send('websocket-closed', code, reason);
        });
        this.reconnect();
      }
    });

    this.ws.on('error', (error) => {
      console.error('WebSocket error:', error);
      BrowserWindow.getAllWindows().forEach((window) => {
        window.webContents.send('websocket-error', error);
      });
      this.reconnect();
    });
  }
  // 主动向服务端推送消息
  sendMessage(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(message);
      console.log('Message sent to server:', message);
    } else {
      console.error('WebSocket connection is not open. Cannot send message.');
    }
  }
  /**
   * 断开Socket链接
   */
  close() {
    this.ws.close();
  }
  // 重新连接方法
  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`Attempting to reconnect (attempt ${this.reconnectAttempts})...`);
      setTimeout(() => {
        this.connect();
      }, this.reconnectInterval);
    } else {
      console.error('Max reconnect attempts reached. Giving up.');
    }
  }
}

module.exports = WebSocketManager;